from asyncio.windows_events import NULL
from io import TextIOWrapper
import os
import json
import re
import chardet


def loadJsonFile(path):
    code = checkFileEncoding(path)
    f = open(path, 'r', encoding=code)

    print(analysisValue(f, None))
    f.close()


def readNoSpaceChar(f: TextIOWrapper):

    char = f.read(1)
    while re.match("\s", char):
        char = f.read(1)
    return char


def analysisKey(f: TextIOWrapper):
    return analyStr(f, readNoSpaceChar(f))


def analysisValue(f: TextIOWrapper, char):
    if char == None:
        char = readNoSpaceChar(f)
    if char == '[':
        return analyList(f)
    elif char == "\"":
        return analyStr(f, char)
    else:
        return analyNumber(f, char)


def analyList(f: TextIOWrapper):
    list = []

    char = readNoSpaceChar(f)

    while char != "]":
        list.append(analysisValue(f, char))
        char = readNoSpaceChar(f)
    return list


def analyStr(f: TextIOWrapper, startChar):
    str = ""
    char = f.read(1)
    while char != startChar:
        str += char
        char = f.read(1)
    return str


def analyNumber(f: TextIOWrapper, num):
    char = f.read(1)
    while re.match("[\d\.]", char):
        num += char
        char = f.read(1)
    if re.match("\d", num):
        return int(num)
    return float(num)


def loadFiles(dirpath):
    files = os.listdir(dirpath)
    for fi in files:
        fi_d = os.path.join(dirpath, fi)
        if os.path.isdir(fi_d):
            loadFiles(fi_d)
        else:
            loadJsonFile(os.path.join(dirpath, fi_d))


def checkFileEncoding(path):
    f = open(path, 'rb')
    data = chardet.detect(f.read())
    f.close()
    return data.get("encoding")


def loadJsonFile2(path):
    code = checkFileEncoding(path)
    print(code)
    with open(path, 'r', encoding=code) as f:
        inJsonStrs = f.readlines()
    inJsonStr = ""
    for line in inJsonStrs:
        i = line.find("//")
        if i != -1:
            inJsonStr += line[0:i]
        else:
            inJsonStr += line

    # inJsonStr = inJsonStr.replace('\r', '')
    # inJsonStr = inJsonStr.replace('\n', '')
    # inJsonStr = inJsonStr.replace(' ', '')
    # inJsonStr = inJsonStr.replace('\000', '')

    jsonObj = json.loads(inJsonStr)
    print(jsonObj)
    return jsonObj